package com.hmbe.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private String name;
    private StringRedisTemplate redisTemplate;
    private static final String KEY_PREFIX = "lock:";

    public SimpleRedisLock(String name, StringRedisTemplate redisTemplate) {
        this.name = name;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Boolean tryLock(long timeout) {
        //1.获取线程id
        String threadId = Thread.currentThread().getId() + "";
        //2.获取锁
        Boolean lock = redisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeout, TimeUnit.SECONDS);
        //3.返回结果
        return Boolean.TRUE.equals(lock);
    }

    @Override
    public void unlock() {
        //1.获取线程id
        String threadId = Thread.currentThread().getId() + "";
        //2.获取锁
        String lockValue = redisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (threadId.equals(lockValue)) {
            redisTemplate.delete(KEY_PREFIX + name);
        }

    }
}
